/* -----------------
* brief
* 1. this is code gen by tools
* 2. for add/update/delete/query the data save in sql database
 */

package eshop

import (
	"github.com/go-xorm/xorm"
	"github.com/mjiulee/lego"
	//"github.com/mjiulee/lego/utils"
	tenant "saas_sys_base/modules/tenant/models"
)

/* 根据id获取记录
 * -----------------
 */
func (t *EShop) RecodeById(id int64) *EShop {
	item := new(EShop)
	_, err := lego.GetDBEngine().ID(id).Get(item)
	if err != nil || item.Id <= 0 {
		return nil
	}
	return item
}

/* 根据id获取记录
 * -----------------
 */
func (t *EShop) RecodeByTenantId(tenantId int64) *EShop {
	item := new(EShop)
	_, err := lego.GetDBEngine().Where("tenant_id = ?", tenantId).Get(item)
	if err != nil || item.Id <= 0 {
		return nil
	}
	return item
}

/* 添加
 * -----------------
 */
func (t *EShop) AddRecode(item2add *EShop) bool {
	item2add.Id = lego.UUID()
	_, err := lego.GetDBEngine().Insert(item2add)
	if err != nil {
		lego.LogError(err)
		return false
	}
	return true
}

func (t *EShop) AddRecodeWithsession(session *xorm.Session, item2add *EShop) bool {
	item2add.Id = lego.UUID()
	_, err := session.Insert(item2add)
	if err != nil {
		lego.LogError(err)
		return false
	}
	return true
}

/* 删除(硬删除)*/
func (t *EShop) DelRecodeById(id int64) bool {
	item := new(EShop)
	_, err := lego.GetDBEngine().ID(id).Delete(item)
	if err != nil {
		lego.LogError(err)
		return false
	}
	return true
}

func (t *EShop) DelRecodeByIdWithSession(session *xorm.Session, id int64) bool {
	item := new(EShop)
	_, err := session.ID(id).Delete(item)
	if err != nil {
		lego.LogError(err)
		return false
	}
	return true
}

/* 更新
 * -----------------*/
func (t *EShop) UpdateRecode(rc *EShop) bool {
	_, err := lego.GetDBEngine().Id(rc.Id).Update(rc)
	if err != nil {
		lego.LogError(err)
		return false
	}
	return true
}

func (t *EShop) UpdateRecodeWithSession(session *xorm.Session, rc *EShop) bool {
	_, err := session.ID(rc.Id).Update(rc)
	if err != nil {
		lego.LogError(err)
		return false
	}
	return true
}

//type ShopItem struct {
//	Id   string
//	ShopName string
//}

func (t *EShop) ListByTenandId(tenandId int64) []*EShopTenant {

	var shopList []*EShopTenant = make([]*EShopTenant, 0)
	session := lego.GetDBEngine().Table("tb_e_shop").Alias("t1").
		Join("left", []string{"tb_tenant", "t2"}, "t1.tenant_id = t2.id").
		Where("t1.if_del = ?", 0).
		And("t2.id = ? or t2.parent_tenant_id = ?", tenandId, tenandId)
	err := session.Find(&shopList)
	if err != nil {
		lego.LogError(err)
	}

	return shopList
}

type EShopTenant struct {
	*EShop         `xorm:"extends"`
	*tenant.Tenant `xorm:"extends"`
}
